package com.ruizhong.centercontroll.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruizhong.centercontroll.dao.TImageMapper;
import com.ruizhong.centercontroll.entity.TCommand;
import com.ruizhong.centercontroll.entity.TImage;
import com.ruizhong.centercontroll.entity.TSwitch;
import com.ruizhong.centercontroll.service.TCommandService;
import com.ruizhong.centercontroll.service.TImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class TImageServiceImpl extends ServiceImpl<TImageMapper, TImage> implements TImageService {

    /**
     * @param
     * @param isNew
     * @return
     * @Description: 保存新的图片列表
     * @version v1.0
     * @author fengweijie
     * @date 2024/12/6 15:27
     */
    @Override
    @Transactional
    public void saveNewImageList(List<Map<String, Object>> imageList, Integer pageId, boolean isNew) {
        deleteImagesByPageId(pageId);
        final HashMap<Integer, List<Map<String, Object>>> imageIdMapInitCommandList = new HashMap<>();

        imageList.forEach(imageOB -> {
            Object src = imageOB.get("src");
            TImage tImage = new TImage();
            tImage.setPageId(pageId);
            tImage.setSrc(src == null ? null : src.toString());
            tImage.setW(Double.parseDouble(imageOB.get("w").toString()));
            tImage.setH(Double.parseDouble(imageOB.get("h").toString()));
            tImage.setX(imageOB.get("x") == null?0:Double.parseDouble(imageOB.get("x").toString()));
            tImage.setY(imageOB.get("y") == null?0:Double.parseDouble(imageOB.get("y").toString()));
            tImage.setZ(Integer.parseInt(imageOB.get("z").toString()));
            Object displayVariableName = imageOB.get("displayVariableName");
            Object displayVariableValue = imageOB.get("displayVariableValue");
            tImage.setDisplayVariableName(displayVariableName == null ? null : displayVariableName.toString());
            tImage.setDisplayVariableValue(displayVariableValue == null ? null : displayVariableValue.toString());
            Object conditionShow = imageOB.get("conditionShow");
            tImage.setConditionShowData(conditionShow == null ? null : (Boolean) conditionShow ? 1 : 0);
            List<Map<String, Object>> initCommandList = null;
            Map logicGraph = (Map) imageOB.get("logicGraph");
            if (!isNew) {
                initCommandList = (List<Map<String, Object>>) imageOB.get("initCommandList");
            } else {
                ObjectMapper mapper = new ObjectMapper();
                try {
                    String logicGraphString = mapper.writeValueAsString(logicGraph);
                    tImage.setLogicGraphData(logicGraphString);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                Map<String, List> typeMapCommandList = TCommandServiceImpl.getCommandsByGraph(logicGraph);
                initCommandList = typeMapCommandList.get("initCommandList");
            }
            save(tImage);
            imageIdMapInitCommandList.put(tImage.getId(), initCommandList);
        });
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                tCommandService.saveCommandList("IMAGE", "init", imageIdMapInitCommandList);
            }
        };
        new Thread(runnable).start();
    }

    @Autowired
    private TCommandService tCommandService;

    /**
     * @param
     * @return
     * @Description: 根据页面ID删除图片组件
     * @version v1.0
     * @author fengweijie
     * @date 2024/12/6 15:29
     */
    @Override
    public void deleteImagesByPageId(Integer pageId) {
        List<TImage> list = lambdaQuery()
                .select(TImage::getId)
                .eq(TImage::getPageId, pageId)
                .list();
        Set<Integer> imgIds = list.stream().map(TImage::getId).collect(Collectors.toSet());
        QueryWrapper<TImage> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.lambda().eq(TImage::getPageId, pageId);
        remove(deleteWrapper);
        tCommandService.delCommandsByMain(imgIds, "IMAGE");
    }

    /**
     * @param
     * @param display
     * @return
     * @Description: 根据页面ID获取对应的图片组件
     * @version v1.0
     * @author fengweijie
     * @date 2024/12/6 15:29
     */
    @Override
    public List<TImage> getImagesByPageId(Integer pageId, Double pageWidth, Double pageHeight, Double aimPageWidth, Double aimPageHeight, Boolean display) throws JsonProcessingException {
        List<TImage> images = lambdaQuery()
                .eq(TImage::getPageId, pageId)
                .list();
        for (TImage image : images) {
            if (!display){
                String logicGraphData = image.getLogicGraphData();
                if (!StringUtils.isEmpty(logicGraphData)){
                    ObjectMapper mapper = new ObjectMapper();
                    Map map = mapper.readValue(logicGraphData, Map.class);
                    image.setLogicGraph(map);
                }
                List<TCommand> initCommands = tCommandService.getCommandListByMain(image.getId(), image.getType(), "init");
                initCommands = tCommandService.fillTCommands(initCommands);
                image.setInitCommandList(initCommands);
            }
            if (aimPageHeight != -1 && aimPageWidth != -1) {
                image.setW(Math.floor((image.getW() * aimPageWidth) / pageWidth));
                image.setH(Math.floor((image.getH() * aimPageHeight) / pageHeight));
                image.setX(Math.floor((image.getX() * aimPageWidth) / pageWidth));
                image.setY(Math.floor((image.getY() * aimPageHeight) / pageHeight));
            }
            image.setConditionShow(image.getConditionShowData() == null ? false : image.getConditionShowData() == 1);
        }
        return images;
    }

    @Override
    public List<TImage> getImageIdsByPageId(Integer pageId) {
        List<TImage> list = lambdaQuery()
                .select(TImage::getId)
                .eq(TImage::getPageId, pageId)
                .list();
        return list;
    }
}
